package com.tusuo.stds.ui.avatar;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.flyco.dialog.widget.NormalDialog;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.tusuo.stds.Constants;
import com.tusuo.stds.R;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import myandroid.library.util.ApplicationHelper;
import rx.functions.Action0;
import timber.log.Timber;


@EActivity(R.layout.activity_avatar)
public class AvatarActivity extends BaseToolbarActivity<AvatarView, AvatarPresenter>
                                implements AvatarView, TakePhoto.TakeResultListener, InvokeListener {

    @ViewById(R.id.avatar_iv)
    ImageView ivAvatar;

    @StringRes(R.string.toolbar_title_avatar)
    String toolbarTitle;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    private ProgressDialog mUploadImgProgressDlg;
    private final int CAMERA_AND_PIC = 101;
    private ActionSheetDialog mDialog;
    private int mCurrentPosition = 0;
    private NormalDialog permissionDialog;

    @AfterViews
    void afterViews() {
        getTakePhoto().onCreate(null);

        setupUI(this, toolbarBgColor, toolbarTextColor);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("更多选择", new Action0() {
            @Override
            public void call() {
                final String[] stringItems = {"拍照", "从系统相册选择"};
                mDialog = new ActionSheetDialog(AvatarActivity.this, stringItems, null);
                mDialog.isTitleShow(false).show();

                mDialog.setOnOperItemClickL(new OnOperItemClickL() {
                    @Override
                    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                        mCurrentPosition = position;
                        checkPermission();
                    }
                });
            }
        }, R.drawable.ic_more);

        menuActionList.add(menuAction);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, true, R.drawable.ic_back_dark, menuActionList);
        mToolbarOwner.setConfig(config);

        String avatarPath = getIntent().getStringExtra("avatar");
        if (!TextUtils.isEmpty(avatarPath)) {
            String imgUrl = Utils.getCorrectImageUrl(avatarPath);

                Glide
                        .with(this)
                        .load(imgUrl)
                        .into(ivAvatar);
        } else {
            Glide
                    .with(this)
                    .load(R.drawable.img_avatar_default_large)
                    .into(ivAvatar);
        }

        ApplicationHelper.getInstance().addActivity(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @NonNull
    @Override
    public AvatarPresenter createPresenter() {
        return new AvatarPresenter(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (permissionDialog != null) {
            permissionDialog.superDismiss();
            permissionDialog = null;

        }
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }
        super.onDestroy();
    }

    @Override
    public void loadAvatar(String imgUrl) {
        if (!TextUtils.isEmpty(imgUrl)) {
            Glide
                    .with(this)
                    .load(Utils.getCorrectImageUrl(imgUrl))
                    .into(ivAvatar);
        }
    }

    protected TakePhoto takePhoto;
    protected InvokeParam invokeParam;;

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    /**
     * 检查是否获取读写SD卡权限,并发起请求
     * @return
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                    ) {

                requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA,
                }, CAMERA_AND_PIC);
            } else {
                getPic();
            }
        } else {
            getPic();
        }
    }

    private void getPic() {

        File file=new File(Environment.getExternalStorageDirectory(), "/tusuo/avatar.jpg");
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        CropOptions cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(true).create();
        CompressConfig compressConfig = new CompressConfig.Builder().setMaxSize(50 * 1024).setMaxPixel(800).create();

        TakePhoto takePhoto = getTakePhoto();
        takePhoto.onEnableCompress(compressConfig, false);

        switch (mCurrentPosition) {
            case 0:
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                break;
            case 1:
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);

//                                MultiImageSelector.create()
//                                        .showCamera(true) // 是否显示相机. 默认为显示
//                                        .single() // 单选模式
//                                        .start(AvatarActivity.this, REQUEST_IMAGE);
                break;
        }

        mDialog.dismiss();

    }


    private void showDisablePermissionDialog() {
        permissionDialog = new NormalDialog(this);

        permissionDialog.isTitleShow(false)
                .btnNum(1)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content("无法使用相册\n请在\"设置\"中开启存储卡和相机权限")
                .contentGravity(Gravity.CENTER)
                .contentTextSize(13)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("确定")
                .btnTextSize(15.5f)
                .btnTextColor(Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .show();

        permissionDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
//                        IntentUtils.toSystemPermissionActivity(mActivity);
                permissionDialog.dismiss();
            }
        });

    }

    @Override
    public void takeSuccess(TResult result) {
        presenter.handleImageSelectResult(result.getImage().getOriginalPath(), mUploadImgProgressDlg);

        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();

        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("完成", new Action0() {
            @Override
            public void call() {
                AvatarActivity.this.finish();
            }
        }, 0);

        menuActionList.add(menuAction);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, true, R.drawable.ic_back_dark, menuActionList);
        mToolbarOwner.setConfig(config);
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Timber.e("f");
    }

    @Override
    public void takeCancel() {
        // TODO: 图片尺寸过大而产生OOM内存溢出
//        Utils.UI.showToastShort("图片尺寸过大\n请上传小于3M的图片");
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(this,type,invokeParam,this);

        switch(requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case CAMERA_AND_PIC:
                boolean granted = true;
                for (int i : grantResults) {
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        granted = false;
                        break;
                    }
                }

                if(granted) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    getPic();
                }
                else{
                    // 没有获取到权限，做特殊处理
                    showDisablePermissionDialog();
                }
                break;
            default:
                break;
        }

    }
}
